package com.nc.delivery_project.server.service;

import com.nc.delivery_project.server.dao.AbstractDao;
import com.nc.delivery_project.server.dao.PaymentDao;
import com.nc.delivery_project.server.db_util.ConnectionManager;
import com.nc.delivery_project.server.domain.Currency;
import com.nc.delivery_project.server.domain.Payment;
import com.nc.delivery_project.server.util.CRUD;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Natalie D.
 * Date: 1/17/15
 * Time: 10:37 PM
 */
public class PaymentService extends BaseService<Payment> {

    private CurrencyService currencyService;

    public PaymentService() {
        this(new PaymentDao());
    }

    public PaymentService(Connection connection, boolean isAutoCloseConnection) {
        super(new PaymentDao(), connection, isAutoCloseConnection);
    }

    public PaymentService(AbstractDao<Payment> dao) {
        super(dao);
    }
    @Override
    public Payment read(int id)
    {
        Payment payment = null;

        try
        {
            Connection conn = getConnection();
            dao.setConnection(conn);
            payment = dao.read(id);
            if (payment != null)
            {
                Currency currency = new CurrencyService(conn, false).read(payment.getCurrency().getId());
                if (currency != null)
                {
                    payment.setCurrency(currency);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                closeConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return payment;
    }

    @Override
    public List<Payment> read()
    {
        List<Payment> payments = null;
        try
        {
            Connection conn = getConnection();
            dao.setConnection(conn);
            payments = dao.read();
            currencyService = new CurrencyService(conn, false);
            for (Payment payment : payments)
                payment.setCurrency(currencyService.read(payment.getCurrency().getId()));

        }

        catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                closeConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return payments;
    }

}

